package com.tm.pojo;

import javax.persistence.Id;

import org.json.JSONObject;

import com.google.appengine.api.datastore.Entity;
import com.googlecode.objectify.annotation.Unindexed;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Price implements Comparable<Price> {
	@Id Long priceId;
	Long instrumentId;
	Date date;
	@Unindexed Double price;
	
	public Price() {
	}
	
	public Price(Entity e) {
		this.setPriceId(e.getKey().getId());
		this.setInstrumentId((Long) e.getProperty("instrumentId"));
		this.setDate((Date) e.getProperty("date"));
		this.setPrice((Double) e.getProperty("price"));
	}
	
	public Long getPriceId() {
		return priceId;
	}
	public Long getInstrumentId() {
		return instrumentId;
	}
	public Date getDate() {
		return date;
	}
	public Double getPrice() {
		return price;
	}

	public void setPriceId(Long priceId) {
		this.priceId = priceId;
	}
	public void setInstrumentId(Long instrumentId) {
		this.instrumentId = instrumentId;
	}
	public void setDate(Date date) {
		this.date = date;
	}
	public void setPrice(Double price) {
		this.price = price;
	}
	public int compareTo(Price o) {
		return (this.date.compareTo(o.getDate()) * (-1));
	}
	
	public String getFormatedDate() {
		if (date == null) {
			return "no date";
		} else {
			SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");
			return(dateFormat.format(date.getTime()));
		}
	}
	public String getFormatedPrice() {
		if (price.isNaN()) {
			return "NaN";
		} else {
			DecimalFormat df = new DecimalFormat("#0.0000");
	        return(df.format(price));
		}
	}
	
	public void setPrice(String price) throws Exception {
		if (price == null) {
			throw new Exception("price is empty");
		}
		this.price = Double.parseDouble(price);
	}
	public void setDate(String date) throws ParseException {
		if (date == null || date.trim().length() == 0) {
			this.date = new Date();
		} else {
			DateFormat df = new SimpleDateFormat("dd/MM/yy");
			this.date = df.parse(date);
		}
	}
	public void setInstrumentId(String instrumentId) {
		this.instrumentId = Long.parseLong(instrumentId);
	}
	
	@SuppressWarnings("finally")
	public JSONObject toJSONObject() {
		JSONObject json = new JSONObject();
		try { 
			json.put("priceId", priceId);
			json.put("instrumentId", instrumentId);
			DateFormat df = new SimpleDateFormat("dd/MM/yy");
			json.put("date", df.format(date));
			json.put("price", price);
		} catch (Throwable e) {
			
		} finally {
			return json;
		}
	}
	
	@Override
	public boolean equals(Object obj) {
		return this.priceId == ((Price)obj).getPriceId();
	}
}
